/*
 * Jmp3PlayerView.java
 */
package jmp3player;

import Dane.Mp3File;
import Dane.Mp3Tree;
import Dane.Settings;
import Watki.Mp3Find;
import Watki.Mp3ListRefresher;
import java.awt.Component;
import java.awt.event.MouseEvent;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Vector;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.tree.TreePath;

/**
 * Główne okno aplikacji
 * @author lukeh
 * @version 2.0
 */
public class Jmp3PlayerView extends FrameView
  {

    /**
     * Konstrukor częścniowo generowany automatycznie
     * @param app
     */
    public Jmp3PlayerView(SingleFrameApplication app)
        {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener()
          {

            public void actionPerformed(ActionEvent e)
                {
                statusMessageLabel.setText("");
                }
          });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++)
            {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
            }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
          {

            public void actionPerformed(ActionEvent e)
                {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
                }
          });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
          {

            public void propertyChange(java.beans.PropertyChangeEvent evt)
                {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName))
                    {
                    if (!busyIconTimer.isRunning())
                        {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                        }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                    } else if ("done".equals(propertyName))
                    {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                    } else if ("message".equals(propertyName))
                    {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                    } else if ("progress".equals(propertyName))
                    {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                    }
                }
          });
        //Pobieramy plik ustawień
        set = new Settings();
        set.getSetFile();

        //Tworzymy nowe drzewo utworów
        mt = new Mp3Tree();

        //Dodajemy akcje do drzewa utworów
        musicTree.addMouseListener(new MouseListener()
          {

            public void mouseClicked(MouseEvent e)
                {
                if (e.getButton() == 3)//kliknięcie prawym przyciskiem
                    {
                    x = e.getX();
                    y = e.getY();
                    pm.show((Component) e.getSource(), x, y);

                    }
                }

            public void mousePressed(MouseEvent arg0)
                {
                // throw new UnsupportedOperationException("Not supported yet.");
                }

            public void mouseReleased(MouseEvent arg0)
                {
                //throw new UnsupportedOperationException("Not supported yet.");
                }

            public void mouseEntered(MouseEvent arg0)
                {
                // throw new UnsupportedOperationException("Not supported yet.");
                }

            public void mouseExited(MouseEvent arg0)
                {
                //throw new UnsupportedOperationException("Not supported yet.");
                }
          });

        playlist = new Vector<Mp3File>();

        }


    /**
     * Wyświetlenie okna informacyjnego "O programie"
     */
    @Action
    public void showAboutBox()
        {
        if (aboutBox == null)
            {
            JFrame mainFrame = Jmp3PlayerApp.getApplication().getMainFrame();
            aboutBox = new Jmp3PlayerAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
            }
        Jmp3PlayerApp.getApplication().show(aboutBox);
        }

    /**
     * Wyświetlenie okna dialogowego pozwalającego na otwieranie plików typu MP3
     */
    @Action
    public void showOpenDlg()
        {
       
            JFrame mainFrame = Jmp3PlayerApp.getApplication().getMainFrame();
            StringBuffer addr = new StringBuffer(".mp3");
            odlg = new openDlg(mainFrame, addr);
            odlg.setLocationRelativeTo(mainFrame);
                            
            
        Jmp3PlayerApp.getApplication().show(odlg);
((Odtwarzacz) toolBar).setFileToPlay(addr.toString());
        ((Odtwarzacz) toolBar).Play();
        }

    /**
     * Wyświetlanie okna ustawień programu
     */
    @Action
    public void showUstawienia()
        {
        if (ust == null)
            {
            JFrame mainFrame = Jmp3PlayerApp.getApplication().getMainFrame();
            ust = new Ustawienia(mainFrame, set);
            ust.setLocationRelativeTo(mainFrame);
            }
        Jmp3PlayerApp.getApplication().show(ust);
        }

    /**
     * Odświeżanie biblioteki multimedów - przeszukanie dysu
     */
    @Action
    public void refreshLib()
        {
        Mp3ListRefresher lr = new Mp3ListRefresher(this);
        Mp3Find mf = new Mp3Find(set, mt, lr);
        new Thread(mf).start();

        }

    /**
     * Odświeżenie drzewa (w nowym wątku)
     */
    @Action
    synchronized public void rfshTree()
        {
        Mp3ListRefresher lr = new Mp3ListRefresher(this);
        new Thread(lr).start();
        }

    /**
     * Odświeżenie drzewa
     */
    @Action
    synchronized public void refreshTree()
        {

        mt.getTreeFile();

        root.removeAllChildren();
        root.add(mt.genNode());
        musicTree.updateUI();
        }
/**
 * Odtwarzanie utworu wybranego z drzewa multimediów
 */
    @Action
    public void playMp3()
        {

        TreePath path = musicTree.getPathForLocation(x, y);
        if (path == null || path.getPathCount() < 5)
            {
            JOptionPane.showMessageDialog(null, "Nie wybrano utworu!");
            return;
            }
        String addr = mt.findFile(path.getPathComponent(2).toString(), path.getPathComponent(3).toString(), path.getPathComponent(4).toString());
        System.out.println(path);
        System.out.println(addr);
        ((Odtwarzacz) toolBar).setFileToPlay(addr);
        ((Odtwarzacz) toolBar).Play();
        }
/**
 * Dodanie utworu z drzewa do kolejki
 */
    @Action
    public void addQ()
        {
        TreePath path = musicTree.getPathForLocation(x, y);
        if (path == null)
            {
            JOptionPane.showMessageDialog(null, "Nie wybrano utworu!");
            return;
            }
        if (path == null || path.getPathCount() < 5)
            {
            JOptionPane.showMessageDialog(null, "Nie wybrano utworu!");
            return;
            }
        String addr = mt.findFile(path.getPathComponent(2).toString(), path.getPathComponent(3).toString(), path.getPathComponent(4).toString());
        Mp3File tmp = new Mp3File(addr);
        System.out.println(addr);
        playlist.add(tmp);
        model.add(model.size(), tmp.Tytul + " - " + tmp.Autor);
        }
    //   }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        root = new DefaultMutableTreeNode("Multimedia");
        musicTree = new javax.swing.JTree(root);
        jScrollPane2 = new javax.swing.JScrollPane();
        Lista = new javax.swing.JList();
        toolBar = new Odtwarzacz();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        pm = new javax.swing.JPopupMenu();
        addToQ = new javax.swing.JMenuItem();
        graj = new javax.swing.JMenuItem();

        mainPanel.setMaximumSize(new java.awt.Dimension(500, 600));
        mainPanel.setName("mainPanel"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jSplitPane1.setDividerLocation(200);
        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        musicTree.setEditable(true);
        musicTree.setName("musicTree"); // NOI18N
        musicTree.setScrollsOnExpand(true);
        musicTree.setSelectionModel(null);
        jScrollPane1.setViewportView(musicTree);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        model = new DefaultListModel();
        Lista.setModel(model);
        Lista.setName("Lista"); // NOI18N
        Lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cliclPlaylista(evt);
            }
        });
        Lista.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                delFromPlaylista(evt);
            }
        });
        jScrollPane2.setViewportView(Lista);

        jSplitPane1.setRightComponent(jScrollPane2);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 463, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 211, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        toolBar.setFloatable(false);
        toolBar.setRollover(true);
        toolBar.setName("toolBar"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(jmp3player.Jmp3PlayerApp.class).getContext().getActionMap(Jmp3PlayerView.class, this);
        fileMenu.setAction(actionMap.get("showUstawienia")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jmp3player.Jmp3PlayerApp.class).getContext().getResourceMap(Jmp3PlayerView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        jMenuItem1.setAction(actionMap.get("showOpenDlg")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N

        jMenuItem2.setAction(actionMap.get("showUstawienia")); // NOI18N
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenu1.add(jMenuItem2);

        jMenuItem3.setAction(actionMap.get("refreshLib")); // NOI18N
        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        jMenu1.add(jMenuItem3);

        jMenuItem4.setAction(actionMap.get("rfshTree")); // NOI18N
        jMenuItem4.setText(resourceMap.getString("jMenuItem4.text")); // NOI18N
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        jMenu1.add(jMenuItem4);

        menuBar.add(jMenu1);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addGap(210, 210, 210)
                        .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE))
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addComponent(statusMessageLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 277, Short.MAX_VALUE)
                        .addComponent(statusAnimationLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addGap(3, 3, 3))
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pm.setName("pm"); // NOI18N

        addToQ.setAction(actionMap.get("addQ")); // NOI18N
        addToQ.setText(resourceMap.getString("addToQ.text")); // NOI18N
        addToQ.setName("addToQ"); // NOI18N
        pm.add(addToQ);

        graj.setAction(actionMap.get("playMp3")); // NOI18N
        graj.setText(resourceMap.getString("graj.text")); // NOI18N
        graj.setName("graj"); // NOI18N
        pm.add(graj);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents
/**
 * Przygotowanie utworu z listy do odegrania
 * @param evt
 */
    private void cliclPlaylista(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cliclPlaylista
        ((Odtwarzacz) toolBar).setFileToPlay(playlist.get(Lista.getSelectedIndex()).Adres);
    }//GEN-LAST:event_cliclPlaylista
/**
 * Usunięcie utworu z listy
 * @param evt
 */
    private void delFromPlaylista(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_delFromPlaylista
        if (evt.getKeyCode() == 127)
            {
            model.remove(Lista.getSelectedIndex());
            }
    }//GEN-LAST:event_delFromPlaylista

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList Lista;
    private javax.swing.JMenuItem addToQ;
    private javax.swing.JMenuItem graj;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTree musicTree;
    private javax.swing.JPopupMenu pm;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    /**Okno "O programie"*/
    private JDialog odlg;
    /**Okno dialogowe otwierania plików*/
    private JDialog ust;
    /**Okno dialogowe ustawień*/
    File settingsFile;
    /**Uchwyt pliku z ustawieniami*/
    Settings set;
    /**Klasa przechowująca ustawienia*/
    DefaultMutableTreeNode root;
    /**Korzeń drzewa multimediów*/
    Mp3Tree mt;
    /**Drzewo multimediów*/
    int x, y;/**Współrzędne kliknięcia*/
    DefaultListModel model;/**Model listy*/
    Vector<Mp3File> playlist;/**Wektor przechowujący utwory w liscie*/
  }
